package com.free.bsf.health.memoryParse;

import com.free.bsf.core.base.Ref;
import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.health.collect.MemoryParseCollectTask;
import com.free.bsf.health.config.HealthProperties;
import lombok.Getter;
import lombok.val;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Classname MemoryRecordUtil
 * @Description
 * @Date 2021/5/12 15:12
 * @Created by chejiangyi
 */
public class MemoryRecordUtils {
    @Getter
    private static RequestHashMap requestHashMap = new RequestHashMap();
    @Getter
    private static ReferenceHashMap referenceHashMap = new ReferenceHashMap();

    private static Integer sum(Object result){
        if(!PropertyUtils.getPropertyCache(HealthProperties.BsfHealthMemoryParseEnabled,false))
            return 0;
        ObjParser objParser = new ObjParser();
        ObjParser.ObjInfo objInfo = objParser.parse(result);
        if(objInfo.getObjs().size()>0) {
            requestHashMap.put(objInfo);
            referenceHashMap.put(objInfo);
        }
        val size = objInfo.getObjs().size();
        objInfo.clear();
        return size;
    }

    public static long checkResultSize(Object result){
        if(result==null)
            return 0;
        val maxsize = MemoryRecordUtils.sum(result);
        return maxsize;
    }

    public static List<Map.Entry<String,Long>> getRequestReport(Ref<Long> total){
        val r = requestHashMap.getReport();
        val report = r.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry<String,Long>::getValue).reversed())
                .filter(c->c.getValue()>0)
                .limit(20)
                .collect(Collectors.toList());
        total.setData(r.entrySet().stream().mapToLong(c->c.getValue()).sum());
       return report;
    }


    public static List<Map.Entry<String,Long>> getPhantomReport(Ref<Long> total){
        val r = referenceHashMap.getReport();
        val report = r.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry<String,Long>::getValue).reversed())
                .filter(c->c.getValue()>0)
                .limit(20)
                .collect(Collectors.toList());
        total.setData(r.entrySet().stream().mapToLong(c->c.getValue()).sum());
        return report;
    }

    public static String getReport(){
        return new MemoryParseCollectTask().getReportNow().toHtml();
    }
}
